#include "hv/hv.h"
#include "hv/hloop.h"

#include "signal.h"
#include <iostream>

#define PORT (9999)
#define N    (10)

#define SIGCUSTOM (41)

sig_atomic_t signaled = 0;

void on_close(hio_t *io) {
    LOGI("Connection closed. fd: %d", hio_fd(io));
}


void on_recv(hio_t *io, void *buf, int readbytes) {
    LOGI("[ RECV(fd: %d) ]: buf: %s, len: %d", hio_fd(io), buf, readbytes);
    hio_write(io, buf, readbytes);
}


void on_accept(hio_t *io) {
    hio_setcb_close(io, on_close);
    hio_setcb_read(io, on_recv);

    LOGI("Connection made. fd: %d", hio_fd(io));

    hio_read(io);
}


void on_sig_int(int sig) {
    std::cerr << "[ on_sig_int ] recved sig: " << sig << " ..." << std::endl;
    signaled = 1;
}


void on_sig_custom(int sig) {
    printf("[ on_sig_custom ] recved sig: %d\n", sig);
}


void thd_loop(void *arg) {
    LOGW("Begin run hv loop, port: %d", PORT);

    hloop_t *loop = hloop_new(0);
    hio_t *io = create_tcp_server(loop, "0.0.0.0", PORT, on_accept);
    if (io == NULL) {
        LOGE("Failed create tcp io!");
    } else {
        hloop_run(loop);
        hloop_free(&loop);
    }

    std::cerr << "[ WARN ] Recv stop signal, stop hv loop." << std::endl;
}


void prexit() {
    LOGW("[ prexit ] All finished. exiting...");
}


int main(int argc, char *argv[]) {
    logger_set_handler(hlog, stdout_logger);
    logger_enable_color(hlog, 1);

    signal(SIGINT, on_sig_int);
    signal(SIGCUSTOM, on_sig_custom);

    /*
    HANDLE h = (HANDLE)_beginthread(thd_loop, 0, NULL);
    if (h == NULL)
        return -1;

    int tid = GetThreadId(h);
    LOGI("Main Loop running... tid: %d", tid);
    */

    atexit(prexit);

    int i = 0;
    while (!signaled) {
        sleep(1);

        if (++i >= N) {
            LOGI("i: %d, raise SIGINT.", i);
            kill(0, SIGINT);
        } else {
            LOGI("running... i: %d, raise custom ev: %d", i, SIGCUSTOM);
            kill(0, SIGCUSTOM);
        }
    }

    LOGE("Exited.");

    return 0;
}
